#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"

/*队列：多个发送任务，发送到同一个队列，一个接收任务*/

void sendTask1(void *pvParameters)
{
    // 队列句柄
    QueueHandle_t QHandle;
    QHandle = (QueueHandle_t)pvParameters;

    // 发送状态
    BaseType_t xStatus;
    int i = 111;

    while (1)
    {
        xStatus = xQueueSend(QHandle, &i, 0); // 注意这里传入的还是指针地址
        if (xStatus == pdPASS)
        {
            // 成功发送
            printf("sendTask: %d\n", i);
        }
        else
        {
            // 发送失败
            printf("sendTask: failed\n");
        }
        // xUSB.id++;
        // xUSB.data++;

        vTaskDelay(pdMS_TO_TICKS(3000));
    }
}

void sendTask2(void *pvParameters)
{
    // 队列句柄
    QueueHandle_t QHandle;
    QHandle = (QueueHandle_t)pvParameters;

    // 发送状态
    BaseType_t xStatus;
    int i = 222;

    while (1)
    {
        xStatus = xQueueSend(QHandle, &i, 0); // 注意这里传入的还是指针地址
        if (xStatus == pdPASS)
        {
            // 成功发送
            printf("sendTask: %d\n", i);
        }
        else
        {
            // 发送失败
            printf("sendTask: failed\n");
        }
        // xUSB.id++;
        // xUSB.data++;

        vTaskDelay(pdMS_TO_TICKS(3000));
    }
}

void recvTask(void *pvParameters)
{
    QueueHandle_t QHandle;
    QHandle = (QueueHandle_t)pvParameters;

    BaseType_t xStatus;
    int i;

    while (1)
    {
        xStatus = xQueueReceive(QHandle, &i, portMAX_DELAY); // portMAX_DELAY如果没有数据传入就会一直阻塞
        if (xStatus == pdPASS)
        {
            // 成功接收
            // printf("recvTask: id=%d; data=%d\n", xUSB.id, xUSB.data);
            printf("recvTask: %d\n", i);
        }
        else
        {
            // 接收失败
            printf("recvTask: failed\n");
        }
    }
}

void app_main(void)
{
    QueueHandle_t QHandle;

    QHandle = xQueueCreate(5, sizeof(int));
    if (QHandle != NULL)
    {
        printf("QHandle is not NULL\n");
        xTaskCreate(sendTask1, "sendTask", 2048, (void *)QHandle, 1, NULL);
        xTaskCreate(sendTask2, "sendTask", 2048, (void *)QHandle, 1, NULL);
        // 接收任务的优先级比发送高，接收任务阻塞，只有当发送任务发送数据时，接收任务才会接收数据
        xTaskCreate(recvTask, "recvTask", 2048, (void *)QHandle, 5, NULL);
    }
    else
    {
        printf("QHandle is NULL\n");
    }
}
